import Axios from 'axios'
import { DateFormat } from 'yb-tool'
import API from '../../api/apis'
import Vue from 'vue'

const YBLOG_DEFAULT_TAG = 'YBLOG_DEFAULT_TAG'

/**
 * 获取默认标记(变于识别是那个人)
 */
function getDefaulrTag() {
  const data = localStorage.getItem(YBLOG_DEFAULT_TAG)
  if (data) {
    return data
  }
  const tag = `${DateFormat(new Date())}-${Math.random()}`
  localStorage.setItem(YBLOG_DEFAULT_TAG, tag)
  return tag
}

class YBLog {

  constructor() {
    /**
     * 用户
     * @type {null}
     * @private
     */
    this.userName = ''
    /**
     * 默认的标记，记录整个流程
     */
    this._defaultTag = getDefaulrTag()
    /**
     * 平台
     */
    this.userAgent = navigator.userAgent
  }


  /**
   * 添加流程记录
   */
  addProcess(router) {
    Axios.post(API.logs.addWebProcess, {
      "routerPath": router.path,
      "routerQuery": JSON.stringify(router.query),
      "routerParams": JSON.stringify(router.params),
      "routerName": router.name,
      "userAgent": this.userAgent,
      "userName": this.userName,
      "defaultTag": this._defaultTag
    }).then(() => {}).catch(() => {})
  }

  /**
   * 添加Ajax日志
   */
  addAjax(ajaxData) {
    const data = {
      defaultTag: this._defaultTag,
      userName: this.userName,
      ...ajaxData,
      userAgent: this.userAgent
    }
    Axios.post(API.logs.addWebAjax, data).then(() => {}).catch(() => {})
  }

  /**
   * 添加错误日志
   */
  addError(errData) {
    const data = {
      ...errData,
      userAgent: this.userAgent,
      defaultTag: this._defaultTag,
      userName: this.userName,
    }
    Axios.post(API.logs.addWebError, data).then(() => {}).catch(() => {})
  }
}

const yb_log = new YBLog()
window.yb_log = yb_log.addLogs

Vue.config.errorHandler = function (err, vm, info) {
  yb_log.addError({
    errMsg: err.message,
    info: info,
    domClass: (vm && vm.$el) ? vm.$el.className : '',
    routerPath: vm.$route.path
  })
}

export default yb_log
